package hangler

import (
	"cmspro/cache"
	"cmspro/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := models.News{
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		//设置缓存
		redis_key := "news_id" + strconv.Itoa(int(data.ID))
		var news models.News
		models.DB.Where("id = ?", data.ID).First(&news)            //查询数据
		jsonData, _ := json.Marshal(news)                          //转化为json数据
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2) //保存到redis
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}
}

func Del(c *gin.Context) {
	id := c.Query("id")
	models.DB.Where("id = ?", id).Debug().Delete(&models.News{})
	//删除缓存
	redis_key := "news_id" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {

	var news []models.News
	models.DB.Find(&news)

	redis_key := "news_list"

	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &news)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": news,
	})
	return
}
